package services;

import dao.ArticleInfoDao;
import models.ArticleInfo;
import models.UserInfo;
import utils.ResultJSONUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:咭咭熊
 * Date:2021 - 08 - 05
 * Time:14:52
 */
@WebServlet("/addart")
public class AddServlet extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int succ = -1;//succ = 1表示操作成功
        String msg = "";//错误说明信息
        //1.得到前端传递的参数
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        //todo:非空校验

        HttpSession session = req.getSession(false);
        if(session != null && session.getAttribute("userinfo") != null){//说明是登录状态，才能添加文章
            UserInfo userInfo = (UserInfo) session.getAttribute("userinfo");
            //2.调用数据库执行相应的业务逻辑
            ArticleInfoDao articleInfoDao = new ArticleInfoDao();
            try {
                succ = articleInfoDao.add(title,content,userInfo.getId());
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }else{
            msg = "非登录状态，请先登录";
        }

        //3.返回结果
        HashMap<String,Object> ret = new HashMap<>();
        ret.put("succ",succ);
        ret.put("msg",msg);
        ResultJSONUtils.write(resp,ret);

    }
}
